import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

import Api, { login, logout ,getAgoraRTMToken} from '@/api/configure.js';
import { deepClone ,mergeUrls, getUserInfo , getRegistrationID} from '@/util/util.js';

import push from '@/store/push.js';

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		userInfo: {},
		agoraRTMToken: null
	},
	mutations: {
		login(state, {userInfo}) {
			state.hasLogin = true;
			state.userInfo = userInfo;
		},
		logout(state) {
			state.hasLogin = false
			state.userInfo = {};
		},
		getUserInfo(state, {userInfo}) {
			state.userInfo = userInfo;
		},
		getAgoraRTMToken(state, {token}) {
			state.agoraRTMToken = token;
		}
	},
	actions: {
		async login({commit, state}, {data}) {
			return await new Promise((resolve, reject) => {
				login(data).then(async ( res ) => {
					let userInfo = res.data;
					
					commit({type: 'login', userInfo: deepClone(userInfo)});
					uni.setStorageSync('userInfo', deepClone(userInfo));
					uni.setStorageSync('userName', data.username);
					uni.setStorageSync('password', data.password);
					data.pushId && uni.setStorageSync('registrationID', data.pushId);
					
					resolve(res.data);
				}, (err) => {
					reject(err)
				});
			})
		},
		async logout({commit, dispatch, state}) {
			return await new Promise(( resolve, reject) => {
				let data = {
					userId: state.userInfo.userId
				}
				
				logout(data).then( async(res) => {
					commit({type: 'logout'});
					uni.removeStorageSync('userInfo');
					uni.removeStorageSync('userName');
					uni.removeStorageSync('password');
					uni.removeStorageSync('registrationID');
					uni.reLaunch({
					    url: '/pages/login/login'
					});
					
					resolve(res);
				}, (err) => {
					reject(err)
				})
			})
		},
		async getUserInfo({commit, dispatch, state}) {
			return await new Promise(( resolve, reject) => {
				let userInfo = deepClone(uni.getStorageSync('userInfo'));
				
				commit({type: 'getUserInfo', userInfo: userInfo});
				
				resolve(state.userInfo)
			})
		},
		async getAgoraRTMToken({commit, dispatch, state}) {
			return await new Promise( async(resolve, reject) => {
				let {userId} = await dispatch('getUserInfo');
				
				let params = {
					userId
				}
				
				let {code, msg: token} = await getAgoraRTMToken(params);
				
				commit({type: 'getAgoraRTMToken', token});
				
				resolve(token);
			})
		}
	},
	modules: {push}
});
export default store;